﻿#define DEBUG_AGENT


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Scheduler;
using System.IO.IsolatedStorage;


namespace MyDemos.Demos
{
    public partial class TileDemo : PhoneApplicationPage
    {


        PeriodicTask periodicTask;
        string periodicTaskName = "PeriodicAgent";
        public bool agentsAreEnabled = true;


        public TileDemo ()
        {
            InitializeComponent ();

        }

        private void Button_Click (object sender, RoutedEventArgs e)
        {
            StandardTileData NewTileData = new StandardTileData
                {
                    Title = "Title2",
                    // BackgroundImage = new Uri (textBoxBackgroundImage.Text, UriKind.RelativeOrAbsolute),
                    Count = 55,
                    BackTitle = "BackTitle",
                    //  BackBackgroundImage = new Uri (textBoxBackBackgroundImage.Text, UriKind.Relative),
                    BackContent = "BackContent"

                };

            ShellTile.Create (new Uri ("/Demos/TileDemo.xaml",UriKind.Relative), NewTileData);


        }

        private void button2_Click (object sender, RoutedEventArgs e)
        {
            StandardTileData NewTileData = new StandardTileData
            {
                Title = "Title2",
                // BackgroundImage = new Uri (textBoxBackgroundImage.Text, UriKind.RelativeOrAbsolute),
                Count = 55,
                BackTitle = "BackTitle",
                //  BackBackgroundImage = new Uri (textBoxBackBackgroundImage.Text, UriKind.Relative),
                BackContent = "BackContent"

            };

            ShellTile.Create (new Uri ("/Demos/TileDemo.xaml?123", UriKind.Relative), NewTileData);

        }

        private void StartPeriodicAgent ()
        {
            // Variable for tracking enabled status of background agents for this app.
            agentsAreEnabled = true;

            // Obtain a reference to the period task, if one exists
            periodicTask = ScheduledActionService.Find (periodicTaskName) as PeriodicTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update 
            // the schedule
            if (periodicTask != null)
            {
                RemoveAgent (periodicTaskName);
            }

            periodicTask = new PeriodicTask (periodicTaskName);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.
            periodicTask.Description = "This demonstrates a periodic task.";

            // Place the call to Add in a try block in case the user has disabled agents
            try
            {
                ScheduledActionService.Add (periodicTask);

                PeriodicStackPanel.DataContext = periodicTask;

                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if(DEBUG_AGENT)
                ScheduledActionService.LaunchForTest (periodicTaskName, TimeSpan.FromSeconds (60));
#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains ("BNS Error: The action is disabled"))
                {
                    MessageBox.Show ("Background agents for this application have been disabled by the user.");
                    agentsAreEnabled = false;
                }
                if (exception.Message.Contains ("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.
                }
                PeriodicCheckBox.IsChecked = false;
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
                PeriodicCheckBox.IsChecked = false;
            }
        }

        private void RemoveAgent (string name)
        {
            try
            {
                ScheduledActionService.Remove (name);
            }
            catch (Exception)
            {
            }
        }


        bool ignoreCheckBoxEvents = false;

        private void PeriodicCheckBox_Checked (object sender, RoutedEventArgs e)
        {
            if (ignoreCheckBoxEvents)
                return;
            StartPeriodicAgent ();
        }

        private void PeriodicCheckBox_Unchecked (object sender, RoutedEventArgs e)
        {
            if (ignoreCheckBoxEvents)
                return;
            RemoveAgent (periodicTaskName);
        }


        protected override void OnNavigatedTo (System.Windows.Navigation.NavigationEventArgs e)
        {
            ignoreCheckBoxEvents = true;

            periodicTask = ScheduledActionService.Find (periodicTaskName) as PeriodicTask;

            if (periodicTask != null)
            {
                PeriodicStackPanel.DataContext = periodicTask;
            }

            ignoreCheckBoxEvents = false;



            if (IsolatedStorageSettings.ApplicationSettings.Contains ("MyTask"))
            {
                IsolatedStorageSettings.ApplicationSettings.Remove ("MyTask");
                List<DateTime> _List = new List<DateTime> ();
                _List.Add (new DateTime (2000, 10, 10, 10, 10, 10));
                IsolatedStorageSettings.ApplicationSettings["MyTask"] = _List;
            }
            else
            {
                List<DateTime> _List = new List<DateTime> ();
                _List.Add (new DateTime (2000, 10, 10, 10, 10, 10));
                IsolatedStorageSettings.ApplicationSettings["MyTask"] = _List;
            }
        }
    }
}